package per.dg.socketservice;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                creatServiceSocket();
            }
        }).start();
    }

    private void creatServiceSocket(){
        try {
            ServerSocket serverSocket = new ServerSocket(2222);

            while (true){
                socket = serverSocket.accept();
                if(socket != null){
                    Log.e(TAG, "creatServiceSocket: "+"接收到客户端的 socket" );
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Log.e(TAG, "run: "+"服务器正在读取信息" );
                            InputStream inputStream = socket.getInputStream();
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                            String receive = null;
//                            while ((receive = bufferedReader.readLine()) != null){
//                                Log.e(TAG, "run: " + receive );
//                            }
                            byte[] buf = new byte[1024];
                            int len = 0;
                            while ((len = inputStream.read(buf)) != -1) {
                                Log.e(TAG, "run: " + new String(buf, 0, len) );
                            }
                            Log.e(TAG, "run: "+"服务器读取信息结束" );

                            Log.e(TAG, "run: "+"服务器正在发送信息" );
                            OutputStream outputStream = socket.getOutputStream();
                            outputStream.write("111111111111111".getBytes());
                            outputStream.flush();
                            Log.e(TAG, "run: "+"服务器发送信息结束" );
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}